import '../css/goodsinfo.css';
import '../fonts/iconfont.css';
import ajax from '../untils/ajax';

toTop();
function toTop() {
    const topBtn = document.getElementById("barTotop");
    topBtn.onclick = function () {
        console.log('top');
        let timer = null;
        cancelAnimationFrame(timer);
        timer = requestAnimationFrame(function fn() {
            let oTop = document.body.scrollTop || document.documentElement.scrollTop;
            if (oTop > 0) {
                scrollTo(0, oTop - 100);
                timer = requestAnimationFrame(fn);
            } else {
                cancelAnimationFrame(timer);
            }
        });
    }
}

showMRL();
function showMRL() {
    const ptpBtn = document.getElementById('headWsale');
    const loginBtn = document.getElementById("topLogin");
    const regBtn = document.getElementById("topReg");
    const goR = document.getElementById('goRegBox');
    const goL = document.getElementById('goLoginBox');
    const NullBtn = document.getElementById('ptpNull');
    const loginBox = document.getElementById('loginBox');
    const regBox = document.getElementById('regBox');
    const ptpBox = document.getElementById('ptp');

    const M = document.getElementById('blackM');

    NullBtn.onclick = function () {
        ptpBox.style.display = 'none';
        M.style.display = 'none';
      }

    ptpBtn.onclick = function () {
        console.log('ptp');
        ptpBox.style.display = 'block';
        M.style.display = 'block';
    }
    loginBtn.onclick = function () {
        console.log('loginBox');
        loginBox.style.display = 'block';
        M.style.display = 'block'
    }
    regBtn.onclick = function () {
        console.log('regBox');
        regBox.style.display = 'block';
        M.style.display = 'block'
    }
    M.onclick = function () {
        M.style.display = 'none';
        ptpBox.style.display = 'none';
        loginBox.style.display = 'none';
        regBox.style.display = 'none';
    }
    goR.onclick = function () {
        loginBox.style.display = 'none';
        regBox.style.display = 'block';
    }
    goL.onclick = function () {
        regBox.style.display = 'none';
        loginBox.style.display = 'block';
    }
}




// fangDaJing();
// function fangDaJing() {
//     var middle = document.getElementsByClassName("middle");
//     var bigbox = document.getElementsByClassName("bigbox");
//     var ceng = null;
//     var wid = null;
//     var bili = 800 / 350;
//     middle[0].onmouseenter = function () {
//         //创建
//         ceng = document.createElement("div");
//         ceng.className = "ceng";
//         //计算层的宽和高
//         wid = 500 / bili;
//         ceng.style.width = wid + "px";
//         ceng.style.height = wid + "px";
//         this.appendChild(ceng);

//         //显示最大容器
//         bigbox[0].style.display = "block";
//     }
//     middle[0].onmouseleave = function () {
//         ceng.remove();
//         //隐藏最大容器
//         bigbox[0].style.display = "none";
//     }
//     middle[0].onmousemove = function (e) {
//         var pageX = e.clientX || e.pageX;
//         var pageY = e.clientY || e.pageY;
//         //下面是使用三元运算符 限制层的移动区域
//         pageX = pageX - wid / 2 < 0 ? 0 : pageX - wid / 2 >= 350 - wid ? 350 - wid : pageX - wid / 2;
//         pageY = pageY - wid / 2 < 0 ? 0 : pageY - wid / 2 >= 350 - wid ? 350 - wid : pageY - wid / 2;
//         ceng.style.left = pageX + "px";
//         ceng.style.top = pageY + "px";

//         //bigbox里面的背景图也跟着移动
//         bigbox[0].style.backgroundPosition = -pageX * bili + "px " + (-pageY * bili) + "px";//如果使用的复合属性 中间的空格别忘了
//     }
// }

test();
function test() {
    const barBtn = document.getElementById('barHelp');
    barBtn.onclick = function () {
        location.assign('goodsinfo.html')
    }
}

haveInfo();
function haveInfo() {
    ajax('get', '/api/users/getGoods').then(result => {
        const goods = document.getElementById('goodsinfoPush').children;
        const kind = document.getElementById('kind');
        const img0 = document.getElementById('gimg');
        console.log(goods);
        let path;

        console.log(result.data);
        let arr = result.data;
        var url0 = location.search;
        let url1 = url0.slice(4);
        console.log(url1);
        for (let i = 0; i < arr.length; i++) {
            if (arr[i]._id == url1) {
                path = arr[i].img.slice(7);
                http://127.0.0.1:3000\\${path}
                img0.src = 'http://127.0.0.1:3000/' + path
                console.log(arr[i]);
                goods[0].innerHTML = arr[i].name;
                goods[1].innerHTML = arr[i].fineness;
                goods[2].innerHTML = arr[i].describe;
                goods[3].innerHTML = '￥' + arr[i].price;
                kind.innerHTML = arr[i].classify;

            }
        }
    })
}

score()
function score() {
    const release = document.querySelector('#myass .release')
    const score = document.querySelector('#assess .score')
    const textarea = document.querySelector('#myass textarea')
    release.onclick = () => {
        let p =document.createElement('p')
        p.innerHTML=textarea.value
        score.prepend(p)
        textarea.value=""   
    }

}

// 图片上传与预览
const form = document.forms[0];
const uploadfile = document.getElementById('uploadfile');


uploadfile.onchange = show_uploadImg;
form.onsubmit = uploadGoods;


if (typeof FileReader == "undified") {
  alert("您老的浏览器不行了！");
}




function show_uploadImg() {
  var resultFile = document.getElementById("uploadfile").files[0];
  if (resultFile) {
    var reader = new FileReader();
    reader.readAsDataURL(resultFile);
    reader.onload = function (e) {
      var urlData = this.result;
      document.getElementById("result").src = urlData;
      // document.getElementById("result").alt= resultFile.name ;



    }

  }
}



function uploadGoods(e) {

  e.preventDefault();
  const xhr = new XMLHttpRequest();
  const fd = new FormData(form);

  xhr.open('post', 'api/users/addgoods', true);

  xhr.send(fd);

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        alert("发布成功")
        location.assign("index.html")
      } else {
        console.log('错误')
      }
    }
  };

}

login_reg();
function login_reg() {
  const regBox = document.querySelector('#regBox');
  const loginBox = document.querySelector('#loginBox');
  const form = document.querySelector('#regBox form');
  const form2 = document.querySelector('#loginBox form');

  form.onsubmit = e => {
    e.preventDefault();
    const username = form.username.value;
    const password = form.password.value;
    ajax('post', '/api/users/reg?', { username, password }).then(result => {
      if (result.flag) {
        alert('注册成功，请登录');
        regBox.style.display = "none"
        loginBox.style.display = "block"
      } else {
        alert(result.msg);
        form.username.select();
        form.username.focus();
      }
    }).catch(err => {
      alert('服务器出错', err);
    })

  }

  form2.onsubmit = e => {
    e.preventDefault();
    const username = form2.username.value;
    const password = form2.password.value;
    if (username && password) {
      ajax('post', '/api/users/login', {
        username: form2.username.value,
        password: form2.password.value
      }).then(result => {
        if (result.flag) {
          alert('登录成功')
          localStorage.setItem('token', result.token);
          location.assign('index.html')
        } else {
          alert(result.msg)
        }
      })
    } else {
      alert('请填写表单每一项')
    }
  }
}

toggle();
function toggle() {
  const toggle = document.querySelector('.toggle');
  const bow = document.querySelector('#bow');
  const bowReg = document.querySelector('#bowReg');
  const clear = document.querySelector('.clear');
  let login = localStorage.getItem("token")
  bow.style.display = "none"

  if (login) {
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        if (xhr.status == 200) {
          toggle.style.display = "none"
          bow.style.display = "inline-block"
          bowReg.innerHTML = '用户:' + xhr.response.username;
        }
      }
    };

    xhr.open('get', `/api/users/index`, true);
    // 设置请求头
    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
    xhr.responseType = "json";
    xhr.send();
  }

  clear.onclick = () => {
    if (confirm("您是否退出账号")) {
      localStorage.clear()
      alert("已退出")
      location.replace('./')
    }
  }
}